﻿using Bing.Maps;
using MovingChame.WindowsStoreApp.Common;
using MovingChame.WindowsStoreApp.CustomControl;
using MovingChame.WindowsStoreApp.Helpers;
using MovingChame.WindowsStoreApp.Models;
using MovingChameLibrary;
using MovingChameLibrary.EnumTypes;
using MovingChameLibrary.Models;
using MovingChameLibrary.ViewModels;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Windows.Devices.Geolocation;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI;
using Windows.UI.ViewManagement;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;

namespace MovingChame.WindowsStoreApp.UIModule
{
    public sealed partial class CurrentTourMapPage : LayoutAwarePage
    {
        private CurrentTourMapViewModel _viewModel;
        public CurrentTourMapViewModel ViewModel
        {
            get { return this._viewModel; }
            set
            {
                this._viewModel = value;
                this.DataContext = value;
            }
        }

        private MapPin selectedPosition;
        private Pushpin selectedLocationPushpin;
        private Schedule lastSelectedItem;
        private readonly string SelectedColor = Colors.Orange.ToString();
        private readonly string NormalColor = Colors.DarkGreen.ToString();

        public CurrentTourMapPage()
        {
            this.InitializeComponent();

            selectedPosition = new MapPin();
            TourMap.Children.Add(selectedPosition);
        }

        protected override void SaveState(Dictionary<String, Object> pageState)
        {
            Schedule selectedItem = lastSelectedItem;
            pageState["SelectedLocation"] = selectedItem;
        }

        protected async override void LoadState(Object navigationParameter, Dictionary<String, Object> pageState)
        {
            ViewModel = new CurrentTourMapViewModel((int)navigationParameter);

            if (pageState != null && pageState.ContainsKey("SelectedLocation"))
            {
                Schedule location = pageState["SelectedLocation"] as Schedule;
                TourMap.SetView(new Location(location.Latitude, location.Longitude), Constants.Map_DefaultZoomLevel);
            }
            else if (ViewModel.Tour.Schedule.Items.Count == 0)
            {
                Location location = await GetCurrentLocation();
                MapLayer.SetPosition(CurrentPositionPushPin, location);
                TourMap.SetView(location, Constants.Map_DefaultZoomLevel);
            }

            foreach (Schedule tourLocation in ViewModel.Tour.Schedule.Items)
            {
                Pushpin LocationPushPin = new Pushpin()
                {
                    Name = tourLocation.Id.ToString(),
                };
                LocationPushPin.Tapped += LocationPushPin_Tapped;
                TourMap.Children.Add(LocationPushPin);
                Location location = new Location(tourLocation.Latitude, tourLocation.Longitude);
                MapLayer.SetPosition(LocationPushPin, location);
                if (tourLocation.State == LocationState.Visiting)
                {
                    itemListView.SelectedItem = tourLocation;
                    TourMap.SetView(location, Constants.Map_DefaultZoomLevel);
                }
            }
        }

        private void Map_Tapped(object sender, TappedRoutedEventArgs e)
        {
            var mapPosition = e.GetPosition(TourMap);
            Location location;
            TourMap.TryPixelToLocation(mapPosition, out location);
            MapLayer.SetPosition(selectedPosition, location);
        }

        private void itemListView_ItemClick(object sender, ItemClickEventArgs e)
        {
            Schedule selectedItem = e.ClickedItem as Schedule;
            Location location = new Location(selectedItem.Latitude, selectedItem.Longitude);
            TourMap.SetView(location, Constants.Map_DefaultZoomLevel);
            if (lastSelectedItem != null)
                lastSelectedItem.ForegroundColor = NormalColor;
            selectedItem.ForegroundColor = SelectedColor;
            lastSelectedItem = selectedItem;
        }

        private async void GoToCurrentPosition_Click(object sender, RoutedEventArgs e)
        {
            Location location = await GetCurrentLocation();
            MapLayer.SetPosition(CurrentPositionPushPin, location);
            TourMap.SetView(location, Constants.Map_DefaultZoomLevel);
            if (lastSelectedItem != null)
                lastSelectedItem.ForegroundColor = NormalColor;
        }

        private void LocationPushPin_Tapped(object sender, TappedRoutedEventArgs e)
        {
            Infobox.Visibility = Visibility.Visible;
            Schedule tourLocation = ViewModel.Tour.Schedule.Items.Where(o => o.Id.ToString().Equals((sender as Pushpin).Name)).FirstOrDefault();
            InfoboxTitle.Text = tourLocation.Title;
            InfoboxSubtitle.Text = tourLocation.Subtitle;

            Location location = new Location(tourLocation.Latitude, tourLocation.Longitude);
            MapLayer.SetPosition(Infobox, location);
            Point offset = MapHelper.GetInfoboxOffset(location, TourMap, 0);
            MapLayer.SetPositionAnchor(Infobox, offset);
            selectedLocationPushpin = sender as Pushpin;
        }

        private void CloseInfobox_Click(object sender, RoutedEventArgs e)
        {
            Infobox.Visibility = Visibility.Collapsed;
        }

        private async Task<Location> GetCurrentLocation()
        {
            var currentPosition = await GeolocationHelper.GetCurrentLocation();
            Location location = new Location(currentPosition.Coordinate.Latitude, currentPosition.Coordinate.Longitude);
            return location;
        }

        private void DetailButton_Click(object sender, RoutedEventArgs e)
        {
            this.Frame.Navigate(typeof(TourSchedulePage), selectedLocationPushpin.Name);
        }
    }
}